package com.coocaa.typhoon.api.v1.userfile.provider;

import cn.hutool.core.io.file.FileNameUtil;
import com.coocaa.cirrus.common.third.filestore.config.TosProperties;
import com.coocaa.typhoon.api.v1.userfile.cache.TaskProgressCache;
import com.coocaa.typhoon.api.v1.userfile.model.UploadTmpResult;
import com.coocaa.typhoon.api.v1.userfile.model.input.GetTaskDataModel;
import com.coocaa.typhoon.api.v1.userfile.model.input.UploadDataModel;
import com.coocaa.typhoon.api.v1.userfile.model.output.TaskProgressResultModel;
import com.coocaa.typhoon.api.v1.userfile.util.TosUploadFilePathUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author bijiahao
 * @date : 2025/9/18 10:02
 * @description
 */
@Slf4j
@Service
public class UserFileMgrProvider {
    private static final String LOCAL_DIR = System.getenv("LOCAL_UPLOAD_DIR");

    @Autowired
    private TaskProgressCache taskProgressCache;
    @Autowired
    private TosProperties tosProperties;
    @Autowired
    private UserFileAsyncProvider userFileAsyncProvider;

    public UploadTmpResult upload(String taskId, MultipartFile file, String userId, UploadDataModel dataModel) {
        String ext = FileNameUtil.extName(file.getOriginalFilename());
        String fileName = TosUploadFilePathUtil.getFileName(ext);
        String localDir = LOCAL_DIR;
        if (StringUtils.isBlank(localDir)) {
            localDir = tosProperties.getTosLocalDir();
        }
        String fileLocalPath = TosUploadFilePathUtil.getLocalSaveFilePath(localDir, fileName);
        File localSaveFile = new File(fileLocalPath);
        try {
            file.transferTo(localSaveFile);
        } catch (IOException e) {
            log.error("文件转存异常", e);
            return null;
        }
       return userFileAsyncProvider.upload(taskId, localSaveFile, fileLocalPath, userId, dataModel);
    }


    public List<TaskProgressResultModel> progress(GetTaskDataModel data) {
        List<TaskProgressResultModel> res = new ArrayList<>();
        data.getTaskList().forEach(taskInfoModel -> {
            String taskId = taskInfoModel.getTaskId();
            TaskProgressResultModel progressResultModel = taskProgressCache.getTaskProgressCache(taskId);
            if (progressResultModel != null) {
                progressResultModel.setTaskId(taskId);
                res.add(progressResultModel);
            }
        });
        return res;
    }

}
